package com.lyhlmj.oop_client.Style.Buttons.RegisterButton;

import com.lyhlmj.oop_client.ClientOperation.ClientUtil.Client;
import com.lyhlmj.oop_client.Frames.LoginAndRegister.LoginFrame.LoginFrame;
import com.lyhlmj.oop_client.Frames.LoginAndRegister.RegisterFrame.RegisterFrame;
import com.lyhlmj.oop_client.Style.Buttons.GeneralButton;
import com.lyhlmj.oop_client.Utils.Request;
import org.json.JSONObject;

import javax.swing.*;
import java.awt.*;

public class RegisterButton extends GeneralButton {
    private Window owner;

    public RegisterButton(String str, Window owner) {
        super(str);
        this.owner = owner;
    }

    public void doRegister(String username, String password, String confirmPassword) {
        //  注册
        //server填写主机的
        //Client client = new Client("192.168.43.61", 2022);
        // 建立短连接
        Client.client.setServer("192.168.43.61");
        Client.client.setPort(2022);
        Client client = Client.client;

        JSONObject jsonReq = Request.getJsonObject("register", "username", username, "password", password, "confirmPassword", confirmPassword);
        client.send(jsonReq, new Client.Callback() {
            @Override
            public void onResult(int status, String reason, JSONObject data) {
                owner.dispose();  //销毁注册框架
                if (status == 0) {
//                    注册成功
                    JOptionPane.showMessageDialog(owner, reason);  //告知用户登陆成功
                    LoginFrame.initial();  //返回五子棋登录框架
                } else {
//                    注册失败
                    JOptionPane.showMessageDialog(owner, reason);  //告知用户登陆失败,及其原因
                    RegisterFrame.initial();  //返回五子棋注册框架
                }
            }
        });
    }
}
